package 掘金.蛇形填充n阶方阵;

public class Main {
    public static int[][] solution(int n) {
        int[][] matrix = new int[n][n];
        int top = 0, bottom = n - 1, left = 0, right = n - 1;
        int cen = 0, max = n * n, num=1;

        while (cen < (n+1)/2) {
            // 最右侧从上往下
            for (int i = cen; i <= n-cen-1; i++) {
                matrix[i][n-cen-1] = num++;
            }

            // 下边从右到左
            for (int i = n-1-cen-1; i >= cen; i--) {
                matrix[n-1-cen][i] = num++;
            }

            // 左边从下到上
            for (int i = n-1-cen-1; i >= cen; i--) {
                matrix[i][cen] = num++;
            }

            // 上边从左到右
            for (int i = cen+1; i <= n-1-cen-1; i++) {
                matrix[cen][i] = num++;
            }
            cen++;
        }
        printMatrix(matrix);

        return matrix;
    }

    public static void printMatrix(int[][] matrix) {
        for (int[] row : matrix) {
            for (int num : row) {
                System.out.printf("%3d ", num);
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int[][] a1 = solution(4);
        System.out.println(java.util.Arrays.deepEquals(a1, new int[][]{{10, 11, 12, 1}, {9, 16, 13, 2}, {8, 15, 14, 3}, {7, 6, 5, 4}}));

    }
}